package com.wksc.framework.impexp.handler.imp;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.wksc.framework.impexp.constants.IEConstants;
import com.wksc.framework.impexp.constants.PostfixType;
import com.wksc.framework.impexp.template.ImpTemplate;
import com.wksc.framework.impexp.util.ImpExpTools;
import com.wksc.framework.impexp.writer.CsvWriter;
import com.wksc.framework.impexp.writer.Writer;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;

public class ImpCsvHandler extends BaseImpHandler {

	private static final long serialVersionUID = 1L;

	public ImpCsvHandler(ImpTemplate impTemplate) throws BiffException,
			IOException {

		super(impTemplate);
	}

	@Override
	public void writeErrInfo(Map<Integer, String> incorrectInfo)
			throws IOException, BiffException, WriteException {
		// 根据行号读取文件得到字符串数组
		String[] rowData;
		// 写错误文件的writer
		Writer writer = null;
		// 保存读取到的数据
		List<String[]> readData = new LinkedList<String[]>();
		// 保存错误原因的列表
		List<String> errData = new LinkedList<String>();

		/* ====================局部变量定义结束========================== */

		/* 1. 生成待写入的错误信息 */
		for (Entry<Integer, String> infoLine : incorrectInfo.entrySet()) {
			rowData = reader.readByRow(infoLine.getKey());
			// String[] newRowData = new String[rowData.length + 1];
			// 数组的复制
			// for(int i=0;i<rowData.length;i++){
			// newRowData[i] = rowData[i];
			// }
			// 将错误信息添加到读取数据中
			// newRowData[rowData.length] = infoLine.getValue();
			readData.add(rowData);
			// 将错误信息Map中的错误原因取出来
			errData.add(infoLine.getValue());
		}

		/* 2. 创建导入错误信息的写入文件 */
		StringBuffer errFileName = new StringBuffer();
		errFileName.append(ImpExpTools.initTempFilePath())
				.append(impTemplate.getFileName())
				.append(PostfixType.CSV.getPostfixType());
		File errFile = new File(errFileName.toString());

		/* 3. 将错误信息写入错误文件 */
		try {
			writer = new CsvWriter();
			writer.initWriter(errFile, true);
			writer.writeByRows(readData, 0);
			writer.writeByCol(impTemplate.getFullHeader().length, errData);
		} finally {
			writer.close();
		}
		if (!ImpExpTools.dirHavePriv(IEConstants.ERROR_PATH, false, true, false)) {
//			throw new RuntimeException(IEConstants.ERROR_PATH
//					+ "(Access denied!)");
			log.error("Error files can not be generated", new RuntimeException(IEConstants.ERROR_PATH  + "(Access denied!)"));
		}
		/* 4. 将生成的错误文件从临时文件夹移至用户可见的文件夹 */
		//FileTools.moveFile(errFileName.toString(), IEConstants.ERROR_PATH);
	}

	@Override
	public PostfixType getPostfix() {
		return PostfixType.CSV;
	}

	@Override
	protected int getTotalLineNum(File impFile) {
		return reader.countTotalLine();
	}

	@Override
	protected String[] getImpHeader(File impFile) {
		return reader.readByRow(0);
	}

}
